use std::thread;

use actix_web::web;
use redis::{ControlFlow, PubSubCommands};

use crate::ws::server::{ChatServer, ChatServerHandle};

///
/// 订阅 channel_notice 通道
/// 实时推送至 websocket 客户端
///
pub fn sub_channel_notice(
    redis: web::Data<redis::Client>,
    chat_server: web::Data<ChatServerHandle>,
) -> thread::JoinHandle<()> {
    thread::spawn(move || {
        let mut conn = redis.get_connection().unwrap();

        conn.subscribe(&["channel_notice"], |msg| {
            let ch = msg.get_channel_name();
            let payload: String = msg.get_payload().unwrap();
            match payload.as_ref() {
                "00000000" => ControlFlow::Break(()),
                d => {
                    // 当 redis 发布内容为 '00000000' 时断开连接
                    log::debug!("Channel '{}' received '{}'.", ch, d);
                    // 调用 websocket 全局广播至 'main' 房间
                    chat_server.send_notice("main", d);
                    ControlFlow::Continue
                }
            }
        })
        .unwrap();
    })
}
